var express = require("express");
var uunewid = require("uuid");
var router = express.Router();
var qs = require("qs");
var { checkProperty, checkAuth } = require("../utils/utils");
const jwt = require("jsonwebtoken");
var { PUBLICKEY, EXPIRESD } = require("../utils/store");
var moment = require("moment");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");
const axios = require("axios");

var constants = require("../utils/constants");

const { ohana } = require("ohana-node-orm");

const tableName = constants.REGISTEDUSERSTABLE;
const ohana_user = new ohana(tableName);
let fs = require("fs");
const md5 = require("md5");

router.get("/getUserStatistcs", function (req, res, next) {
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  getUserStatistcs().then(result => {
    res.send(result)
  }
  )

})

async function getUserStatistcs() {
  let resultData = {};
  var userIndustryDate = "select INDUSTRY, COUNT(*) as TOTAL from " + constants.REGISTEDUSERSTABLE + " where INDUSTRY != 'initial' group by INDUSTRY"
  const result = await ohana_user.raw(userIndustryDate);
  resultData.industry = result;

  var userQuestion = "select USER_ID,count(*) as TOTAL  from QUESTIONNAIRES where USER_ID is not NULL  group by USER_ID"
  const userResult = await ohana_user.raw(userQuestion);
  var questionnaireData = {
    finished: 0,
    unfinished: 0
  }
  userResult.map(one => {
    if (one.TOTAL == 9) {
      questionnaireData.finished++;
    } else {
      questionnaireData.unfinished++;
    }
  })
  resultData.questionnaire = questionnaireData;
  var dateQuery = "select count(*) as TOTAL from " + constants.REGISTEDUSERSTABLE + " where CREATED_AT between '" + moment().days(-30).format("YYYY-MM") + "' and '" + moment().format("YYYY-MM") + "'"
  console.log(dateQuery)
  var monthlygrowth = await ohana_user.raw(dateQuery);
  resultData.monthlygrowth = monthlygrowth[0].TOTAL;
  return resultData;
  // console.log(result);


}

router.post("/changePassword", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '改密码'
  // #swagger.description = "修改密码"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  const { data } = req.body;
  // console.log(req.body);
  checkAndChangePassword(data).then(result => {
    if (result > 0) {
      res.status(200).send({ message: "success", code: 0 })
    } else {
      res.status(400).send({ message: "密码错误，请重新输入", code: -1 })
    }
  }).catch(err => {
    console.log(err)
    res.sendStatus(500)
  })
})

async function checkAndChangePassword(data) {
  var payload = {
    USER_NAME: data.USER_NAME,
    PASSWORD: data.PASSWORD
  };
  const result = await ohana_user.findOne(payload)
  let resultNew = 0;
  if (result.length > 0) {
    resultNew = await ohana_user.update(payload, { PASSWORD: data.NEW_PASSWORD })
  }
  return resultNew;

}

router.get("/getSubUserInfo", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取子账户信息'
  // #swagger.description = "获取子账户信息 获取子账户信息"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  // console.log(user.company);
  getUserSubaccount(user.company).then(result => {
    res.send(result)
  }).catch(err => {
    log.error(err);
    res.status(500).send(err);
  })


})

async function getUserSubaccount(company) {
  const user = new ohana(tableName); // new ohana('table_name');
  const results = await user.find(["USER_NAME", "PHONE", "DEPARTMENT"], { COMPANY_NAME: company })
  return results;
}
router.get("/userWithQuestionnaire", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = 'userWithQuestionnaire'
  // #swagger.description = "获取单独用户的信息 加上问卷"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);

  if (!user.authCheck) {
    res.sendStatus(403);
  }

  let { USER_ID } = req.query;
  if (USER_ID == undefined) {
    res.status(400).send({
      message: "please add parameter",
    });
  }
  userWithQuestionnaire({ USER_ID: USER_ID })
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function userWithQuestionnaire(condition) {
  const user = new ohana(tableName); // new ohana('table_name');
  let result = await user.find(condition);
  let questionnaire = await user.raw("select * from QUESTIONNAIRES where USER_ID = '" + condition.USER_ID + "'")
  result[0].QUESTIONAIRE = questionnaire;
  return result;
}

router.get("/archive", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '将用户的数据存档'
  // #swagger.description = "目前返回了五大服务，推荐和收藏的数据，可能有其他数据需要保存，文件存在./archiveFile/目录下"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */

  let { USER_ID } = req.query;
  if (USER_ID == undefined) {
    res.status(400).send("请输入USER_ID");
  }
  archive(USER_ID)
    .then((result) => {
      if (result !== undefined) {
        fs.writeFileSync(
          "./archiveFile/" + USER_ID + ".txt",
          JSON.stringify(result)
        );
        res.send(result);
      } else {
        res.sendStatus(500);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function archive(USER_ID) {
  asssetData = await ohana_user.raw(
    "select * from SAP_JIANGDU_ASSETS where USER_ID_USER_ID = '" + USER_ID + "'"
  );
  policyData = await ohana_user.raw(
    "select * from SAP_JIANGDU_POLICYS where USER_ID_USER_ID = '" +
    USER_ID +
    "'"
  );
  talentData = await ohana_user.raw(
    "select * from SAP_JIANGDU_TALENTS where USER_ID_USER_ID = '" +
    USER_ID +
    "'"
  );
  techData = await ohana_user.raw(
    "select * from SAP_JIANGDU_TECH_INNOS where USER_ID_USER_ID = '" +
    USER_ID +
    "'"
  );
  finData = await ohana_user.raw(
    "select * from SAP_JIANGDU_JINRONGHUIQIS where USER_ID_USER_ID = '" +
    USER_ID +
    "'"
  );
  recommendData = await ohana_user.raw(
    "select * from SAP_JIANGDU_RECOMMENDED_LIST where USER_ID = '" +
    USER_ID +
    "'"
  );
  favoriteData = await ohana_user.raw(
    "select * from SAP_JIANGDU_FAVOURITE_LIST where USER_ID_USER_ID = '" +
    USER_ID +
    "'"
  );
  return {
    asssetData: asssetData,
    policyData: policyData,
    talentData: talentData,
    techData: techData,
    finData: finData,
    recommendData: recommendData,
    favoriteData: favoriteData,
  };
}

router.get("/ssologin", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = 'SSOLOGIN 以及刷新Token。无需参数.但是需要JWT token'
  // #swagger.description = 'SSOLOGIN 以及刷新Token。无需参数.但是需要JWT token'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);
  var sqlConn = new ohana(tableName);
  log.info(user);
  if (!user.authCheck) {
    res.sendStatus(401);
  }
  sqlConn
    .findOne({
      USER_ID: user.user_id,
    })
    .then((result) => {
      log.info(result);
      if (result.length > 0) {
        res.send({
          code: 0,
          status: "OK",
          USER_NAME: result[0].USER_NAME,
          COMPANY_NAME: result[0].COMPANY_NAME,
          AUTH: result[0].AUTH,
          USER_ID: result[0].USER_ID,
          token: generateToken({
            USER_NAME: result[0].USER_NAME,
            USER_ID: result[0].USER_ID,
            LEVEL: result[0].LEVEL,
            AUTH: result[0].AUTH,
            status: "ok",
          }),
          message: "passed",
        });
      } else {
        res.send({
          message: "找不到人",
        });
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.delete("/", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '删除user'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
              required: true,
              content: {
                  "application/json": {
                      schema: {
                          $ref: "#/definitions/user_delete"
                      }  
                  },
              }
      } */
  const { data } = req.body;
  deleteUser(data)
    .then((result) => {
      log.info(result);
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(500);
      }
      //return res.send(result)
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});
async function deleteUser(body) {
  const policy = new ohana(tableName);
  const result = await policy.raw(
    'delete from "' + tableName + "\" where USER_ID = '" + body.USER_ID + "'"
  );
  policy.raw(
    'delete from "' + constants.USER_CONFIG_TABLE + "\" where USER_ID = '" + body.USER_ID + "'"
  )
  policy.raw(
    'delete from "' + constants.VIPUSERSCORE + "\" where USER_ID = '" + body.USER_ID + "'"
  )
  return result;
}
/* GET users listing. */
router.get("/", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取User'
  // #swagger.description = '这个API能获取所有User的列表'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = new ohana(tableName); // new ohana('table_name');
  user
    .find()
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

router.get("/avatar", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取User的avatar'
  // #swagger.description = '这个API通过username获取avatar'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */

  // const user = checkAuth(req.user, constants.BASICAUTH);
  // if (!user.authCheck) {
  //   res.sendStatus(403);
  // }

  let { company_name } = req.query;
  if (!company_name) {
    res.status(400).send("need query parameter COMPANY_NAME");
  }
  let ohana_instance = new ohana(tableName);
  let sql =
    "SELECT AVATAR FROM " +
    tableName +
    " WHERE COMPANY_NAME = '" +
    company_name +
    "' AND LEVEL!='L2' AND STATUS='" +
    constants.STATUSCONFIRMED +
    "'";
  ohana_instance
    .raw(sql)
    .then((result) => {
      res.status(200).send(result[0]);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

/* GET users statistics. */
router.get("/statistics", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '根据用户的信息返回信息'
  // #swagger.description = '需要JWT token 返回统计信息。无需参数'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const userNew = checkAuth(req.user, constants.ASSETAUTH);
  getStatistics(userNew)
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});
async function getStatistics(userNew) {
  const user = new ohana(tableName);
  let resultTable = [];
  if (userNew.admin) {
    let tables = [
      constants.POLICYTABLE,
      constants.ASSETTABLE,
      constants.TECHTABLE,
      constants.TALENTTABLE,
      constants.FINTABLE,
      constants.REGISTEDUSERSTABLE,
      constants.RECOMMENDLISTTABLE,
        constants.ALLLOGTABLE
    ];
    var yiFabu = {
      table: "yifabu",
      TOTAL: 0,
    };
    for (var i = 0; i < tables.length; i++) {
      var sqlString = "select count(*) as total from " + tables[i];
      // var yifabuString = sqlString;
      if (userNew.admin != true && userNew.LEVEL == constants.LEVELTWO) {
        sqlString += " where USER_ID_USER_ID = '" + userNew.user_id + "'";
        // yifabuString = sqlString + " and STATUS = 'on'";
      } else if (userNew.admin != true) {
        sqlString += " where COMPANY_NAME = '" + userNew.company + "'";
        // yifabuString = sqlString + " and STATUS = 'on'";
      }
      const result = await user.raw(sqlString);
      // const resultCount = await user.raw(yifabuString);
      resultTable.push({
        table: tables[i],
        TOTAL: result[0].TOTAL,
      });
      yiFabu.TOTAL += result[0].TOTAL;
    }
    resultTable.push(yiFabu);
    //add Company Statistcis
    const companyNumber = "select count(*) as total from " + constants.REGISTEDUSERSTABLE + " where TOKEN = 'USER' and LEVEL !='L2'"
    var companySQL = await user.raw(companyNumber);
    resultTable.push({
      table: "REGISTED_COMPANY",
      TOTAL: companySQL[0].TOTAL
    })

  } else {
    let tables = [
      constants.ASSETTABLE,
      constants.TECHTABLE,
      constants.TALENTTABLE,
    ];
    var sum = {
      table: "sum",
      TOTAL: 0,
    };
    for (var i = 0; i < tables.length; i++) {
      var sqlString = "select count(*) as total from " + tables[i];
      if (userNew.admin != true && userNew.LEVEL == constants.LEVELTWO) {
        sqlString +=
          " where USER_ID_USER_ID = '" +
          userNew.user_id + "'";
          // "' and STATUS = 'on'";
      } else if (userNew.admin != true) {
        sqlString +=
          " where COMPANY_NAME = '" + userNew.company + "'";
          //  and STATUS = 'on'";
      }
      const result = await user.raw(sqlString);
      resultTable.push({
        table: tables[i],
        TOTAL: result[0].TOTAL,
      });
      sum.TOTAL += result[0].TOTAL;
    }
    resultTable.push(sum);
  }
  return resultTable;
}

router.get("/getLastEntries", function (req, res, next) {
  const { days } = req.query;
  const userNew = checkAuth(req.user, constants.ASSETAUTH);
  if (days) {
    getLastEntries(days, userNew)
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    const { startDate, endDate } = req.query;
    if (startDate && endDate) {
      getEntriesByDate(startDate, endDate, userNew)
        .then((result) => {
          res.send(result);
        })
        .catch((err) => {
          log.error(err);
          res.status(500).send(err);
        });
    } else {
      res.send({
        message: "please add parameter",
      });
    }


  }
});
async function getEntriesByDate(startDate, endDate, userNew) {
  const user = new ohana(tableName);
  let resultTable = [];
  let tables = [
    constants.ASSETTABLE,
    constants.POLICYTABLE,
    constants.TECHTABLE,
    constants.TALENTTABLE,
    constants.FINTABLE,
  ];
  if (userNew.admin) {
    tables.push(constants.REGISTEDUSERSTABLE);
    tables.push(constants.RECOMMENDLISTTABLE);
  }
  for (var i = 0; i < tables.length; i++) {
    let sqlUserString = "";
    if (userNew.admin != true) {
      sqlUserString = "USER_ID_USER_ID = '" + userNew.user_id + "' and ";
    }
    // var sqlString =
    //   "select count(*) as TOTAL ,CREATED_AT from (select TO_NVARCHAR(CREATED_AT,'YYYY-MM-DD')  as CREATED_AT from " +
    //   tables[i] +
    //   " where " +
    //   sqlUserString +
    //   "  CREATED_AT > '" +
    //   comparedata +
    //   '\') group by "CREATED_AT" order by CREATED_AT asc';

    // console.log(comparedata);
    var today = moment().format("YYYY-MM-DD");
    var sqlString =
      "select count(*) as TOTAL ,CREATED_AT from (select TO_NVARCHAR(CREATED_AT,'YYYY-MM-DD')  as CREATED_AT from " +
      tables[i] +
      " where " +
      sqlUserString +
      "  CREATED_AT between '" +
      startDate +
      "' and '" + endDate + "') group by CREATED_AT order by CREATED_AT asc"
    const result = await user.raw(sqlString);
    /**
     *
     *
     * SELECT count(*) as TOTAL,CREATED_AT from
     *  (select TO_NVARCHAR(CREATED_AT,'YYYY-MM-DD')as CREATED_AT from "118AF16985A94C8CB7D3AF83453A6879"."SAP_JIANGDU_USERS"  where CREATED_AT > '2021-09-01')
     *  group by "CREATED_AT"
     */
    // console.log(result)
    if (result.length > 0) {
      if (result[0].CREATED_AT && result[0].CREATED_AT != startDate) {
        result.unshift({ TOTAL: 0, CREATED_AT: startDate })
      }
      // console.log(result[result.length - 1]);
      if (result[result.length - 1].CREATED_AT != endDate) {
        result.push({ CREATED_AT: endDate, TOTAL: 0 })
      }
    }
    resultTable.push({
      table: tables[i],
      DETAIL: result,
    });
  }
  return resultTable;



}
async function getLastEntries(days, userNew) {
  const user = new ohana(tableName);
  let resultTable = [];
  let tables = [
    constants.ASSETTABLE,
    constants.POLICYTABLE,
    constants.TECHTABLE,
    constants.TALENTTABLE,
    constants.FINTABLE,
  ];
  if (userNew.admin) {
    tables.push(constants.REGISTEDUSERSTABLE);
    tables.push(constants.RECOMMENDLISTTABLE);
  }
  tables.push(constants.ALLLOGTABLE);
  const comparedata = moment()
    .subtract(parseInt(days), "d")
    .format("YYYY-MM-DD");
  for (var i = 0; i < tables.length; i++) {
    let sqlUserString = "";
    if (userNew.admin != true) {
      sqlUserString = "USER_ID_USER_ID = '" + userNew.user_id + "' and ";
    }
    // var sqlString =
    //   "select count(*) as TOTAL ,CREATED_AT from (select TO_NVARCHAR(CREATED_AT,'YYYY-MM-DD')  as CREATED_AT from " +
    //   tables[i] +
    //   " where " +
    //   sqlUserString +
    //   "  CREATED_AT > '" +
    //   comparedata +
    //   '\') group by "CREATED_AT" order by CREATED_AT asc';

    // console.log(comparedata);
    var today = moment().format("YYYY-MM-DD");
    var todayPlus = moment().add(1, 'd').format("YYYY-MM-DD");
    var sqlString =
      "select count(*) as TOTAL ,CREATED_AT from (select TO_NVARCHAR(CREATED_AT,'YYYY-MM-DD')  as CREATED_AT from " +
      tables[i] +
      " where " +
      sqlUserString +
      "  CREATED_AT between '" +
      comparedata +
      "' and '" + todayPlus + "') group by CREATED_AT order by CREATED_AT asc"
    const result = await user.raw(sqlString);
    /**
     *
     *
     * SELECT count(*) as TOTAL,CREATED_AT from
     *  (select TO_NVARCHAR(CREATED_AT,'YYYY-MM-DD')as CREATED_AT from "118AF16985A94C8CB7D3AF83453A6879"."SAP_JIANGDU_USERS"  where CREATED_AT > '2021-09-01')
     *  group by "CREATED_AT"
     */
    // console.log(result)
    if (result.length > 0) {
      if (result[0].CREATED_AT && result[0].CREATED_AT != comparedata) {
        result.unshift({ TOTAL: 0, CREATED_AT: comparedata })
      }
      // console.log(result[result.length - 1]);
      if (result[result.length - 1].CREATED_AT != today) {
        result.push({ CREATED_AT: today, TOTAL: 0 })
      }
    }
    resultTable.push({
      table: tables[i],
      DETAIL: result,
    });
  }
  return resultTable;
}
// 注册接口
router.post("/register", async (req, res, next) => {
  // #swagger.tags = ['用户']
  // #swagger.summary = '注册User 1.一级用户注册，不能有LEVEL STATUS为 INITiAL。 二级用户注册STATUS为Confirmed LEVEL为L2'
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/user"
                    }  
                },
            }
    } */
  const user = new ohana(tableName);
  const { data } = req.body;
  checkProperty(constants.USERFIELDS, data);
  username = data.USER_NAME;
  data.PASSWORD = data.PASSWORD ? data.PASSWORD : md5('123456');
  try {
    // 查询当前用户名在不在数据库中(使用async方法后必须使用await方法才有值返回，不然返回promise对象)
    founduser = await user.findOne({
      USER_NAME: username,
      // PASSWORD: password,
    });
    // 存在res即是数据库中有数据
    if (founduser && founduser.length != 0) {
      res.status(400).send({
        code: -1,
        msg: "用户已注册",
      });
    } else {
      // 对密码进行加密
      // md5_password = md5(username + password);
      //初始化数据 ： 一级账户
      data.USER_ID = uunewid.v4();
      //注册二级用户
      if (data.LEVEL != constants.LEVELTWO) {
        //一级用户状态为INITIAL 二级则为CONFIRMED 无需审批
        data.LEVEL = 'VIP1';
        data.STATUS = constants.STATUSCOMPANYINPROCESS;
      }
      if (data.LEVEL == constants.LEVELTWO) {
        const foundLevelTwo = await user.find({
          COMPANY_NAME: data.COMPANY_NAME,
          LEVEL: constants.LEVELTWO,
        });
        //检测子账户时候已经超过3个
        if (foundLevelTwo.length >= 3) {
          res.status(200).send({
            code: -1,
            message: "子账户数已经超出",
          });
          return;
        }
        //copy 权限 以及  insert into config 
      }
      data.TOKEN = "USER";
      //data.PASSWORD = md5_password;
      await user.insert(data);
      res.send({
        code: 0,
        msg: "注册成功",
        USER_ID: data.USER_ID,
      });
    }
  } catch (error) {
    log.error(error);
    next(error);
  }
});



router.post("/login", async function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '登录'
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/user_login"
                    }  
                },
            }
    } */

  const { data } = req.body;
  if (!data) {
    res.send({
      code: 400,
      message: constants.BODY_IN_CORRECT,
    });
  }

  const user = new ohana(tableName);
  username = data.USER_NAME;
  password = data.PASSWORD;

  try {
    let res1 = await user.findOne({
      USER_NAME: username,
      PASSWORD: password,
    });
    let res2 = await user.findOne({
      COMPANY_CODE: username,
      PASSWORD: password,
    });
    let res3 = await user.findOne({
      PHONE: username,
      PASSWORD: password,
    });

    let result = [];
    result.push(...res1);
    result.push(...res2);
    result.push(...res3);
    if (result.length == 0) {
      res.sendStatus(401);
      // res.send({
      //   code: 401,
      //   message: "user_password_error",
      // });
      return;
    }
    let real_user_name = result[0].USER_NAME;
    //md5_password = md5(real_user_name + password);
    log.info(real_user_name);
    if (result && result.length != 0) {
      log.info(result[0].COMPANY_NAME);
      let faceData = {
        status: false,
      };
      try {
        faceData = JSON.parse(result[0].FACE_IDENTITY_STATUS);
        if (faceData == null) {
          faceData = {
            status: false,
          };
        }
      } catch (error) {
        log.error("face recogination error");
        log.error(error);
      }
      res.send({
        code: 0,
        status: "OK",
        USER_NAME: real_user_name,
        STATUS: result[0].STATUS,
        COMPANY_NAME: result[0].COMPANY_NAME,
        LEVEL: result[0].LEVEL,
        AUTH: result[0].AUTH,
        USER_ID: result[0].USER_ID,
        USER_TYPE: result[0].TOKEN,
        FACE_IDENTITY_STATUS: faceData.status ? faceData.status : false,
        token: generateToken({
          USER_NAME: real_user_name,
          USER_ID: result[0].USER_ID,
          LEVEL: result[0].LEVEL,
          AUTH: result[0].AUTH,
          USER_TYPE: result[0].TOKEN,
          COMPANY_NAME: result[0].COMPANY_NAME,
          FACE_IDENTITY_STATUS: faceData.status,
          status: "ok",
        }),
        message: "passed",
      });
    } else {
      res.send({
        code: -1,
        msg: "用户名或密码错误！",
      });
    }
  } catch (error) {
    log.error(error);
    next(error);
  }
});

function generateToken(userData) {
  const token =
    "Bearer " +
    jwt.sign(
      {
        _id: userData.USER_ID,
        name: userData.USER_NAME,
        role: userData.AUTH,
        company: userData.COMPANY_NAME,
        level: userData.LEVEL,
        face: userData.FACE_IDENTITY_STATUS,
        userType: userData.TOKEN,
      },
      PUBLICKEY,
      {
        expiresIn: EXPIRESD,
      }
    );
  return token;
}

router.get("/isConfirmed", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '查看当前用户状态'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  getUserStatus(user.user_id)
    .then((result) => {
      let ifConfirmed = result == constants.STATUSCONFIRMED ? true : false;
      res.send(ifConfirmed);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function getUserStatus(user_id) {
  const user = new ohana(tableName);
  let result = await user.find(["STATUS"], {
    USER_ID: user_id,
  });
  return result[0].STATUS;
}
router.get("/getCompanyInfo", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取企业信息'
  // #swagger.description = "返回"USER_ID",  "COMPANY_NAME", "COMPANY_CODE", "COMPANY_TYPE"四个字段"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  getCompanyInfo(req.query)
    .then((result) => {
      if (result !== undefined) {
        res.send(result);
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});
router.post("/getCompanyInfoByCompanyCodeAndFaRen", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '根据法人和企业社会代码获取企业信息'
  // #swagger.description = "返回"USER_ID",  "COMPANY_NAME", "COMPANY_CODE", "COMPANY_TYPE"四个字段"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/getCompanyInfoByCompanyCodeAndFaRen"
                    }  
                },
            }
    } */
  let { data } = req.body;
  console.log(data);
  if (!data.LEGAL_REPRESENTATIVE || !data.COMPANY_CODE) {
    res.status(400).send({
      message: "缺少参数",
      code: -1,
    });
  }
  var payload = {
    client_id: "187cba8e-dc39-4e14-bd0f-489f8627c422",
    client_secret: "c3f0a8fc-041c-44b9-8472-0ada8af7db92",
    grant_type: "client_credentials",
  };
  axios
    .post(
      "http://58.220.131.72:7777/epoint-sso-web/rest/oauth2/token",
      qs.stringify(payload),
      {
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
      }
    )
    .then((result) => {
      axios
        .post(
          "http://58.220.131.70:12230/epoint-gateway/share/qysldjxxcx",
          qs.stringify({
            FR_XM: data.LEGAL_REPRESENTATIVE,
            TYSHXYDM: data.COMPANY_CODE,
          }),
          {
            headers: {
              Authorization: "Bearer " + result.data.custom.access_token,
              "content-type": "application/x-www-form-urlencoded",
            },
          }
        )
        .then((result2) => {
          // console.log(result2)
          if (result2.data[0].totalAmount == 0) {
            res.status(500).send(result2.data);
          } else {
            let formattedResult = {};
            formattedResult.LEGAL_REPRESENTATIVE = result2.data[1].FR_XM;
            formattedResult.ID_NUM = result2.data[1].FR_ZJHM;
            formattedResult.BUSINESS_SCOPE = result2.data[1].JYFW;
            formattedResult.COMPANY_TYPE = result2.data[1].QYLXMC;
            formattedResult.COMPANY_NAME = result2.data[1].QYMC;
            formattedResult.COMPANY_ADDRESS = result2.data[1].QYZS;
            formattedResult.ESTABLISHED_DATE = result2.data[1].SLRQ;
            formattedResult.COMPANY_CODE = result2.data[1].TYSHXYDM;
            formattedResult.REGISTER_NUMBER = result2.data[1].ZCZJ;
            formattedResult.REGISTER_CURRENCY = result2.data[1].ZJBZ;
            res.send(formattedResult);
          }
        })
        .catch((err) => {
          // console.log(err);
          axios
            .post(
              "http://58.220.131.70:12230/epoint-gateway/share/qysldjxxcx",
              qs.stringify({
                FR_XM: data.LEGAL_REPRESENTATIVE,
                TYSHXYDM: data.COMPANY_CODE,
              }),
              {
                headers: {
                  Authorization: "Bearer " + result.data.custom.access_token,
                  "content-type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then((result2) => {
              // console.log(result2)
              if (result2.data[0].totalAmount == 0) {
                res.status(500).send(result2.data);
              } else {
                let formattedResult = {};
                formattedResult.LEGAL_REPRESENTATIVE = result2.data[1].FR_XM;
                formattedResult.ID_NUM = result2.data[1].FR_ZJHM;
                formattedResult.BUSINESS_SCOPE = result2.data[1].JYFW;
                formattedResult.COMPANY_TYPE = result2.data[1].QYLXMC;
                formattedResult.COMPANY_NAME = result2.data[1].QYMC;
                formattedResult.COMPANY_ADDRESS = result2.data[1].QYZS;
                formattedResult.ESTABLISHED_DATE = result2.data[1].SLRQ;
                formattedResult.COMPANY_CODE = result2.data[1].TYSHXYDM;
                formattedResult.REGISTER_NUMBER = result2.data[1].ZCZJ;
                formattedResult.REGISTER_CURRENCY = result2.data[1].ZJBZ;
                res.send(formattedResult);
              }
            }).catch(err => {
              res.status(500).send({
                message: "华为接口",
                code: -1,
                detail: err,
              });
            })

        });
    })
    .catch((err) => {
      console.log(err);
      res.status(500).send({
        message: "axios调用失败",
        code: -1,
        detail: err,
      });
    });
  // getCompanyInfoByFaRen(data)
  //   .then((result) => {
  //     console.log(result)
  //     if (result !== undefined) {
  //       res.send(result);
  //     } else {
  //       res.sendStatus(400);
  //     }
  //   })
  //   .catch((err) => {
  //     log.error(err);
  //     res.status(500).send(err);
  //   });
});

async function getCompanyInfoByFaRen(data) {
  var payload = {
    client_id: "187cba8e-dc39-4e14-bd0f-489f8627c422",
    client_secret: "c3f0a8fc-041c-44b9-8472-0ada8af7db92",
    grant_type: "client_credentials",
  };
  await axios
    .post(
      "http://58.220.131.72:7777/epoint-sso-web/rest/oauth2/token",
      qs.stringify(payload),
      {
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
      }
    )
    .then((result) => {
      console.log("result");
      console.log(result.data.custom.access_token);
      axios
        .post(
          "http://58.220.131.70:12230/epoint-gateway/share/qyjbxx",
          qs.stringify({
            FR: data.LEGAL_REPRESENTATIVE,
            ZCH: data.COMPANY_CODE,
          }),
          {
            headers: {
              Authorization: "Bearer " + result.data.custom.access_token,
              "content-type": "application/x-www-form-urlencoded",
            },
          }
        )
        .then((result2) => {
          console.log(result2.data);
          return result2.data;
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch((err) => {
      console.log(err);
    });
  // const user = new ohana(constants.USERSTABLE); // new ohana('table_name');
  // const result = await user.findOne({
  //   COMPANY_CODE: data.COMPANY_CODE,
  //   LEGAL_REPRESENTATIVE: data.LEGAL_REPRESENTATIVE,
  // });
  // return result;
}
router.post("/getCompanyInfobyCondition", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取企业信息根据选择条件'
  // #swagger.description = ”返回“
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/user_getCompanyInfobyCondition"
                    }  
                },
            }
    } */

  const { data } = req.body;
  getCompanyInfoByCondition(data)
    .then((result) => {
      if (result) {
        res.send(result);
      } else {
        res.sendStatus(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});
router.post("/", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '插入User'
  // #swagger.description = "插入新的企业数据"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/user"
                    }  
                },
            }
    } */
  const { data } = req.body;
  data.USER_ID = uunewid.v4();
  data.CREATED_AT = moment().format("YYYY-MM-DD HH:mm:ss");
  data.UPDATED_AT = moment().format("YYYY-MM-DD HH:mm:ss");
  data.LOG_DATE = moment().format("YYYY-MM-DD HH:mm:ss");
  data.VALIDATEDATE = moment().format("YYYY-MM-DD HH:mm:ss");
  data.HEZHUN_TIME = moment().format("YYYY-MM-DD HH:mm:ss");
  data.TOKEN = "USER";
  data.COMPANY_CODE = "000";
  insertData(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.send(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function insertData(body) {
  const user = new ohana(tableName); // new ohana('table_name');
  const result = await user.insert(body);
  return result;
}

/**
 * Get the company by criterian
 */
router.post("/search", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '搜索企业，query参数未知'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/user_search"
                    }  
                },
            }
    } */
  const queryData = req.query;
  const user = new ohana(tableName); // new ohana('table_name');
  if (queryData == null) {
    user
      .find()
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    user
      .find(queryData)
      .then((result) => {
        res.send(result);
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  }
});

/**
 * Update COMMENTS, STATUS by USER_ID
 * @param {*} body
 * @returns
 */
router.put("/updateStatus", async (req, res, next) => {
  // #swagger.tags = ['用户']
  const { data } = req.body;
  // #swagger.summary = "审批专用"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/user_updateStatus"
                    }  
                },
            }
    } */
  const user = new ohana(tableName);
  try {
    //update set VIP level 1
    data.LEVEL = "VIP1";
    const result = await user.update(
      {
        USER_ID: data.USER_ID,
      },
      data
    );
    if (result == 1) {
      res.sendStatus(200);
    } else {
      res.send(500);
    }
  } catch (err) {
    log.error(err);
  }
});

/**
 * 127.0.0.1:4000/api/users/getCompanyInfo
 * @returns
 */
async function getCompanyInfo(payload) {
  if (payload && payload.type == "all") {
    const user = new ohana(constants.USERSTABLE); // new ohana('table_name');
    const joeResult = await user.find();
    return joeResult;
  }
  const user = new ohana(tableName); // new ohana('table_name');
  var statusString = "STATUS = 'CONFIRMED' or STATUS = 'BLACKLIST'";
  if (payload.type == constants.BACKEND) {
    statusString = "STATUS !='INITIAL'";
  }
  var sqlString = 'SELECT "USER_ID",  "COMPANY_NAME","CREATED_AT", "UPDATED_AT","COMPANY_CODE", "COMPANY_TYPE","STATUS","LEGAL_REPRESENTATIVE","ESTABLISHED_DATE","COMPANY_ADDRESS","INDUSTRY","REGISTER_CURRENCY","PHONE" FROM ' +
    tableName +
    " where (" + statusString + ") and LEVEL !='" +
    // " where (STATUS = 'CONFIRMED' or STATUS = 'BLACKLIST') and LEVEL !='" +
    constants.LEVELTWO +
    "' and TOKEN = 'USER'"
  const result = await user.raw(sqlString);
  return result;
}

/**
 * 127.0.0.1:4000/api/users/getCompanyGeneralInfo
 * @param {*} body
 * @returns
 */
async function getCompanyInfoByCondition(filter) {
  const user = new ohana(tableName); // new ohana('table_name');
  const result = await user.find(["USER_ID", "COMPANY_CODE", "USER_NAME", "COMPANY_NAME", "LEGAL_REPRESENTATIVE", "PHONE", "CREATED_AT", "STATUS", "COMMENTS"], filter);
  return result.filter(
    (one) =>
      checkInitial(one, "COMPANY_CODE") && one.LEVEL != constants.LEVELTWO
  );
}

function checkInitial(data, field) {
  if (data[field] != "initial" && data[field] != " " && data[field] != null) {
    return true;
  } else return false;
}

router.get("/getUserByName", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取 user by name'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */

  let { name } = req.query;
  getUserByName(name)
    .then((result) => {
      if (result !== undefined) {
        res.send(result);
      } else {
        res.sendStatus(400);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function getUserByName(name) {
  const ohana_user = new ohana("SAP_JIANGDU_USERS"); // new ohana('table_name');
  let result = await ohana_user.find({
    COMPANY_NAME: name,
  });
  return result;
}

/***
 * get user info
 *
 */

router.get("/getUsers", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取'
  // #swagger.description = "插入新的企业数据"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /* #swagger.parameters['type'] = {
        description: 'type=ADMIN || USER',
        required: true,
        type: 'integer',
} */

  let { type } = req.query;
  if (type == undefined) {
    type = "all";
  }
  getUserInfo(type)
    .then((result) => {
      if (result !== undefined) {
        res.send(result);
      } else {
        res.sendStatus(500);
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function getUserInfo(filter) {
  const user = new ohana(tableName); // new ohana('table_name');
  let result = [];
  if (filter == "all") {
    result = await user.find(
      ["USER_ID", "USER_NAME", "PHONE", "AUTH", "TOKEN", "COMPANY_NAME", "LEVEL", "CREATED_AT", "UPDATED_AT"],
      {
        STATUS: "CONFIRMED",
      }
    );
  } else {
    result = await user.find(
      ["USER_ID", "USER_NAME", "PHONE", "AUTH", "TOKEN", "COMPANY_NAME", "LEVEL", "CREATED_AT", "UPDATED_AT"],
      {
        TOKEN: filter,
        STATUS: "CONFIRMED",
      }
    );
  }
  return result;
}

router.put("/updateUserPropertyNew", async (req, res, next) => {
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  let { data } = req.body;
  data.UPDATED_AT = moment().format("YYYY-MM-DD HH:mm:ss");
  // console.log(data);
  updateUser(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.status(400).send({
          message: "没有这个用户",
        });
      }
    })
    .catch((err) => {
      console.log(err)
      res.status(500).send(err);
    });
});

router.put("/updateUserProperty", async (req, res, next) => {
  // #swagger.tags = ['用户']
  // #swagger.summary = "更新用户，审批等"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*	#swagger.requestBody = {
            required: true,
            content: {
                "application/json": {
                    schema: {
                        $ref: "#/definitions/user_updateUserProperty"
                    }  
                },
            }
    } */
  let faceReturnStatus = "";
  let { data } = req.body;
  if (!data.hasOwnProperty("USER_ID")) {
    res.status(400).send({
      message: "please add mandantory field USER_ID",
      code: -1,
    });
    return;
  }
  delete data.LEVEL;
  let duplicateCheck = true;
  //检查人脸识别字段
  if (data.FACE_IDENTITY_STATUS) {
    const userAgentData = req.get("User-Agent");
    if (!userAgentData.includes("MicroMessenger")) {
      delete data.FACE_IDENTITY_STATUS;
    }
    //check JSON status
    const faceStatus = data.FACE_IDENTITY_STATUS;
    const userConnect = new ohana(tableName); // new ohana('table_name');
    const userOne = await userConnect.findOne(
      ["LEGAL_REPRESENTATIVE", "ID_NUM"],
      {
        USER_ID: data.USER_ID,
      }
    );
    if (userOne.length > 0) {
      //{status: "REVIEW", name: AAA, number: BBBBBBBBB}）
      //相同的话 更新 以及返回 ok
      console.log(
        faceStatus.number.toString().toUpperCase() ==
        userOne[0].ID_NUM.toString().toUpperCase()
      );
      if (
        faceStatus.name == userOne[0].LEGAL_REPRESENTATIVE &&
        faceStatus.number.toString().toUpperCase() ==
        userOne[0].ID_NUM.toString().toUpperCase()
      ) {
        faceReturnStatus = constants.FACESTATUSOK;
        data.FACE_IDENTITY_STATUS.status = constants.FACESTATUSOK;
        data.FACE_IDENTITY_STATUS = JSON.stringify(data.FACE_IDENTITY_STATUS);
        console.log(data);
        data.STATUS = constants.STATUSCOMPANYINPROCESS;
      } else {
        //不同的话，不更新而且返回review
        faceReturnStatus = constants.FACESTATUSREVIEW;
        data.FACE_IDENTITY_STATUS = JSON.stringify(data.FACE_IDENTITY_STATUS);
      }
    }
  }

  //不可让用户更新状态
  if (data.STATUS == constants.STATUSCONFIRMED) {
    delete data.STATUS;
  }
  if (data.STATUS == constants.STATUSCOMPANYINPROCESS) {
    try {
      //检测是否有已经认证状态的公司
      duplicateCheck = await checkRegisteredOrNot(data);
      if (duplicateCheck) {
        data.STATUS = constants.STATUSCONFIRMED;
        data.LEVEL = "VIP1";
        data.AUTH = "[]";
        //认证通过
      } else {
        data.STATUS = constants.STATUSINITIAL;
      }
    } catch (error) {
      res.status(400).send({
        code: -1,
        message: "错误，用户查询错误",
      });
      return;
    }
  }
  if (duplicateCheck) {
    updateUser(data)
      .then((result) => {
        if (result == 1) {
          if (faceReturnStatus) {
            res.status(200).send({
              status: faceReturnStatus,
            });
          } else {
            res.sendStatus(200);
          }
        } else {
          res.status(400).send({
            message: "没有这个用户",
          });
        }
      })
      .catch((err) => {
        log.error(err);
        res.status(500).send(err);
      });
  } else {
    res.status(200).send({
      message: "已经有用户注册",
      code: -1,
    });
    return;
  }
});
async function checkRegisteredOrNot(data) {
  const user = new ohana(tableName);
  const result = await user.findOne({
    COMPANY_NAME: data.COMPANY_NAME,
    STATUS: constants.STATUSCONFIRMED,
  });
  if (result.length > 0) {
    return false;
  }
  return true;
}
async function updateUser(data) {
  const user = new ohana(tableName); // new ohana('table_name');
  const result = user.update(
    {
      USER_ID: data.USER_ID,
    },
    data
  );
  return result;
}

router.get("/getSingleUser", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = 'getSingleUser'
  // #swagger.description = "获取单独用户的信息"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  if (!req.user) {
    res.sendStatus(403);
    return;
  }
  let { USER_ID } = req.query;
  if (USER_ID == undefined) {
    res.status(400).send({
      message: "please add parameter",
    });
    return;
  }
  getSingleUser(USER_ID)
    .then((result) => {
      if (result.length > 0) {
        res.send(result);
        return;
      } else {
        res.status(400).send({
          message: "No user found",
          code: "noUserFound",
        });
        return;
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});
async function getSingleUser(userData) {
  const user = new ohana(tableName); // new ohana('table_name');
  const result = await user.find({
    USER_ID: userData,
  });
  return result;
}

router.get("/getSubUsers", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = 'getSingleUser'
  // #swagger.description = "获取单独用户的信息"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /* #swagger.parameters['company'] = {
      description: "公司名称",
      required: true,
} 
*/
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  let { company } = req.query;
  if (company == undefined) {
    res.status(400).send({
      message: "please add parameter company",
    });
    return;
  }
  var payload = {
    COMPANY_NAME: company,
    LEVEL: constants.LEVELTWO,
  };
  getSubUsers(payload)
    .then((result) => {
      if (result.length > 0) {
        res.send(result);
        return;
      } else {
        res.status(200).send({
          message: "No user found",
          code: "noUserFound",
        });
        return;
      }
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});

async function getSubUsers(payload) {
  const user = new ohana(tableName); // new ohana('table_name');
  const result = await user.find(payload);
  return result;
}

router.get("/getUserScore", function (req, res, next) {
  // #swagger.tags = ['用户']
  // #swagger.summary = '获取用户评分VIP'
  // #swagger.description = "获取用户评分VIP"
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const userNew = checkAuth(req.user, constants.BASICAUTH);
  if (!userNew.authCheck) {
    /* #swagger.responses[403] = {
        description: '缺少权限'
                } */
    res.sendStatus(403);
    return;
  }
  const user = new ohana(tableName); // new ohana('table_name');
  user
    .raw(
      "select * from SAP_JIANGDU_VIP_USER_SCORES where USER_ID = '" +
      userNew.user_id +
      "'"
    )
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
      res.status(500).send(err);
    });
});
module.exports = router;
